package com.bw.gmall.realtime.dwd.db.split.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.common.base.BaseApp;
import com.bw.gmall.realtime.common.constant.Constant;
import com.bw.gmall.realtime.common.util.DateFormatUtil;
import com.bw.gmall.realtime.common.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SideOutputDataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;
import org.apache.flink.util.StringUtils;

import java.time.Duration;

public class DwdBaseLog extends BaseApp {
    public static void main(String[] args) {
        new DwdBaseLog().start(10011, 4, "topic_log", "dwd_base_log");
    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> kafkaSource) {
//        kafkaSource.print();
        // 1.ETL数据
        SingleOutputStreamOperator<JSONObject> etlStream = etl(kafkaSource);
        // 2. 添加水印并keyby
        KeyedStream<JSONObject, String> keyedStream = etlStream.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3)).withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
            @Override
            public long extractTimestamp(JSONObject jsonObject, long l) {
                // 毫秒
                return jsonObject.getLong("ts");
            }
        })).keyBy(new KeySelector<JSONObject, String>() {
            @Override
            public String getKey(JSONObject jsonObject) throws Exception {
                return jsonObject.getJSONObject("common").getString("mid");
            }
        });
        // 3. 新老用户校验
        SingleOutputStreamOperator<JSONObject> fixIsNewStream = keyedStream.process(new KeyedProcessFunction<String, JSONObject, JSONObject>() {

            private ValueState<String> firstLogin;

            @Override
            public void open(Configuration parameters) throws Exception {
                firstLogin = getRuntimeContext().getState(new ValueStateDescriptor<String>("first_login", String.class));
            }

            @Override
            public void processElement(JSONObject jsonObject, KeyedProcessFunction<String, JSONObject, JSONObject>.Context context, Collector<JSONObject> collector) throws Exception {
                JSONObject common = jsonObject.getJSONObject("common");
                String isNew = common.getString("is_new");
                String firstValue = firstLogin.value();
                Long ts = jsonObject.getLong("ts");
                String curDt = DateFormatUtil.tsToDate(ts);
                // 新用戶
                if ("1".equals(isNew)) {
                    if (firstValue != null && !firstValue.equals(curDt)) {
                        common.put("is_new", 0);
                    } else if (firstValue == null) {
                        firstLogin.update(curDt);
                    } else {
                        // 留空
                    }
                } else if ("0".equals(isNew)) {
                    firstLogin.update(DateFormatUtil.tsToDate(ts - 24 * 60 * 60 * 1000));
                } else {

                }
                collector.collect(jsonObject);
            }
        });
        // 4、分流

        OutputTag<String> startTag = new OutputTag<String>("start", TypeInformation.of(String.class));
        OutputTag<String> errorTag = new OutputTag<String>("err", TypeInformation.of(String.class));
        OutputTag<String> displayTag = new OutputTag<String>("display", TypeInformation.of(String.class));
        OutputTag<String> actionTag = new OutputTag<String>("action", TypeInformation.of(String.class));
        SingleOutputStreamOperator<JSONObject> splitStream = pageStreamSplit(fixIsNewStream, startTag, errorTag, displayTag, actionTag);
        // 5、提取側輸出流
        SideOutputDataStream<String> startStream = splitStream.getSideOutput(startTag);
        SideOutputDataStream<String> errorStream = splitStream.getSideOutput(errorTag);
        SideOutputDataStream<String> displayStream = splitStream.getSideOutput(displayTag);
        SideOutputDataStream<String> actionStream = splitStream.getSideOutput(actionTag);
        // 6、寫到kakfa
        startStream.print("start------------");
        errorStream.print("error---------");
        displayStream.print("display--------");
        actionStream.print("actionStream--------");
        splitStream.print("splitStream--------");
        startStream.sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_START));
        errorStream.sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ERR));
        displayStream.sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_DISPLAY));
        actionStream.sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ACTION));
        splitStream.map(JSONAware::toJSONString).sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_PAGE));

    }

    private SingleOutputStreamOperator<JSONObject> pageStreamSplit(SingleOutputStreamOperator<JSONObject> fixIsNewStream, OutputTag<String> startTag, OutputTag<String> errorTag, OutputTag<String> displayTag, OutputTag<String> actionTag) {
        return fixIsNewStream.process(new ProcessFunction<JSONObject, JSONObject>() {
            @Override
            public void processElement(JSONObject value, ProcessFunction<JSONObject, JSONObject>.Context context, Collector<JSONObject> collector) throws Exception {
                JSONObject err = value.getJSONObject("err");
                if (err != null) {
                    context.output(errorTag, value.toJSONString());
                    value.remove("err");
                }

                JSONObject start = value.getJSONObject("start");
                JSONObject page = value.getJSONObject("page");
                JSONObject common = value.getJSONObject("common");
                Long ts = value.getLong("ts");
                if (start != null) {
                    context.output(startTag, value.toJSONString());
                } else if (page != null) {
                    // 曝光
                    JSONArray displays = value.getJSONArray("displays");
                    if (displays != null){
                        for (int i = 0; i < displays.size(); i++) {
                            JSONObject display = displays.getJSONObject(i);
                            display.put("common",common);
                            display.put("ts", ts);
                            display.put("page", page);
                            context.output(displayTag, display.toJSONString());
                        }
                        value.remove("displays");
                    }
                    // 動作
                    JSONArray actions = value.getJSONArray("actions");
                    if (actions != null){
                        for (int i = 0; i < actions.size(); i++) {
                            JSONObject action = actions.getJSONObject(i);
                            action.put("common",common);
                            action.put("ts", ts);
                            action.put("page", page);
                            context.output(actionTag, action.toJSONString());
                        }
                        value.remove("actions");

                    }
                    // 頁面
                    collector.collect(value);
                }
            }
        });
    }

    private SingleOutputStreamOperator<JSONObject> etl(DataStreamSource<String> kafkaSource) {
        return kafkaSource.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {
                JSONObject jsonObject = JSON.parseObject(s);
                // common ts  mid
                JSONObject start = jsonObject.getJSONObject("start");
                JSONObject common = jsonObject.getJSONObject("common");
                JSONObject page = jsonObject.getJSONObject("page");
                String mid = common.getString("mid");
                Long ts = jsonObject.getLong("ts");
                if (page != null || start != null) {
                    if (mid != null && ! mid.equals("") && ts != null) {
                        collector.collect(jsonObject);
                    }
                }
            }
        });
    }
}
